﻿#region  Copyright (C) 2013 Unisys Corporation

// =============================================================================================
// All Rights Reserved. This work contains trade secrets and confidential material of UNISYS, 
// and its use or disclosure in whole or in part without explicit written permission of 
// UNISYS is prohibited. 
//  
// Product Name          :  Unisys e-Workflow and Imaging
// File Name             :  fMain.cs
// Authored By           :  Unisys Corporation
// =============================================================================================
//	Modified by                         Date            Version
// =============================================================================================
//	ronald.aguilar@cr.unisys.com      Jun 06, 2013    Initial Version
// =============================================================================================
#endregion

#region Using Region
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Win32;
using System.Configuration;
using Unisys.DuplicateCheck.Data;
using Unisys.DuplicateCheck.Entity;
using Unisys.DuplicateCheck.Entity.Model;
using Unisys.DuplicateCheck.Entity.Helper;
using Unisys.DuplicateCheck.Logic;
using Unisys.DuplicateCheck.Logic.Services;
using System.Xml;

#endregion

namespace TestSplashScreen
{
    public partial class fMain : Form
    {
        delegate void AsyncMethodCaller();
        private IAsyncResult result;
        IAsyncResult result0;
        AsyncMethodCaller caller;
        AsyncMethodCaller application;
        DuplicateService dupli = new DuplicateService();

        public fMain()
        {
            InitializeComponent();
            this.Load += new EventHandler(fMain_Load);
            Service.eventWriteInWindows  += new Service.writeInWindows(Bitacora);
        }

        void fMain_Load(object sender, EventArgs e)
        {
            showSplashScreen();

            #region Load Configuration Fields

            txt_BussinessRules.Text = Configuration.duplicateRules;
            txt_LogLocation.Text = Configuration.logLocation;
            txt_LogMaxSizeBytes.Text = Configuration.logMaxSizeBytes.ToString();
            txt_ReadCommand.Text = Configuration.readCommand;
            txt_StringConnection.Text = Configuration.stringConnection;
            txt_UpdateCommand.Text = Configuration.updateCommand;
            txt_Sistema.Text = Configuration.systemID;
            txt_TimeOut.Text = Configuration.timeOutQuery.ToString();
            if (Configuration.Information_Message == true)
            {
                cbx_Information.Checked = true;
            }

            if (Configuration.Error_Message == true)
            {
                cbx_Error.Checked = true;
            }

            if (Configuration.Log_Message == true)
            {
                cbx_Log.Checked = true;
            }

            if (Configuration.Process_Message == true)
            {
                cbx_Process.Checked = true;
            }

            #endregion

            DeserializerFile();





            #region Exceptions
            #endregion

            #region Inconsistencies
            #endregion

            #region Rejecteds
            #endregion

        }

        private void showSplashScreen()
        {
            using (fSplashScreen fsplash = new fSplashScreen())
            {
                if (fsplash.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) this.Close();
            }
        }

        private void btn_Logs_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.SelectedPath = "C:\\";
            DialogResult result = folderBrowserDialog1.ShowDialog();
            if (result.ToString() == "OK")
            {
                txt_LogLocation.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void txt_LogMaxSizeBytes_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Char.IsDigit(e.KeyChar))
            {
                e.Handled = false;
            }
            else if (Char.IsControl(e.KeyChar))
            {
                e.Handled = false;
            }
            else if (Char.IsSeparator(e.KeyChar))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

        private void btn_RN_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "Xml Files|*.xml;*.XML";
            DialogResult result = openFileDialog1.ShowDialog();
            if(result.ToString() == "OK")
            {
                txt_BussinessRules.Text = openFileDialog1.FileName;
            }

        }

        private void btn_SaveConfig_Click(object sender, EventArgs e)
        {
            try
            {

                Configuration.SaveConfig(txt_LogLocation.Text.Trim(),
                    Convert.ToInt32(txt_LogMaxSizeBytes.Text.Trim()),
                    txt_StringConnection.Text.Trim(),
                    txt_Sistema.Text.Trim(),
                    txt_ReadCommand.Text.Trim(),
                    txt_UpdateCommand.Text.Trim(),
                    txt_BussinessRules.Text.Trim(),
                    true, true, true, true,Convert.ToInt32(txt_TimeOut.Text.Trim()));
                MessageBox.Show("Configuracion guardada con exito");
            }
            catch (Exception exc)
            {
                MessageBox.Show(string.Format("No se pudo guardar la configuracion, error: {0}",exc.Message));   
            }

            
        }

        private void Bitacora(string args)
        {
           
           txt_Bitacora.Text += args + " \n ";
              
        }

        private void btn_Iniciar_Click(object sender, EventArgs e)
        {
           
            if ((verifyConfig()))
            {    
                Administrator admin = new Administrator();
                
                pgb_BarProcess.Style = ProgressBarStyle.Marquee;
                lbl_Progress.Text = "...Iniciando";
                AsyncMethodCaller application = new AsyncMethodCaller(admin.ProcessManager);
                
                    // Initiate the asychronous call.
                
               result0 = application.BeginInvoke(null, null);

                application.EndInvoke(result0);
                lbl_Progress.Text = ".Proceso Finalizado";

                pgb_BarProcess.Style = ProgressBarStyle.Blocks;
                
             
                
            }
            
        }


        private bool verifyConfig()
        {
            //BusinessRules
            if (txt_BussinessRules.Text.Trim().Equals(""))
            { 
                MessageBox.Show("El campo 'Reglas de Negocio' NO puede estar vacío. \n Por favor verifique e intente de nuevo.", "Unisys Duplicate Check", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            else { Configuration.duplicateRules = txt_BussinessRules.Text.Trim();}

            //LogLocation
            if (txt_LogLocation.Text.Trim().Equals(""))
            {
                { MessageBox.Show("El campo 'Localización de Logs' NO puede estar vacío. \n Por favor verifique e intente de nuevo.", "Unisys Duplicate Check", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
                }

            }
            else { Configuration.logLocation = txt_LogLocation.Text.Trim(); }

            //LogMaxSizeBytes
            if (txt_LogMaxSizeBytes.Text.Trim().Equals(""))
            {
                { MessageBox.Show("El campo 'Tamaño máximo de log' NO puede estar vacío. \n Por favor verifique e intente de nuevo.", "Unisys Duplicate Check", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
                }

            }
            else{Configuration.logMaxSizeBytes = Convert.ToInt32(txt_LogMaxSizeBytes.Text.Trim());}

            //StringConnection
            if (txt_StringConnection.Text.Trim().Equals(""))
            {
                MessageBox.Show("El campo 'String Connection' NO puede estar vacío. \n Por favor verifique e intente de nuevo.", "Unisys Duplicate Check", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            else{ Configuration.stringConnection = txt_StringConnection.Text.Trim();}

            //System_ID
            if (txt_Sistema.Text.Trim().Equals(""))
            {
                MessageBox.Show("El campo 'ID de Sistema' NO puede estar vacío. \n Por favor verifique e intente de nuevo.", "Unisys Duplicate Check", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            else{Configuration.systemID = txt_Sistema.Text.Trim();}
            

            Configuration.topQuery = "100";

            //UpdateCommand
            if (txt_UpdateCommand.Text.Trim().Equals(""))
            {
                MessageBox.Show("El campo 'Update Command' NO puede estar vacío. \n Por favor verifique e intente de nuevo.", "Unisys Duplicate Check", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            else{Configuration.updateCommand = txt_UpdateCommand.Text.Trim();}
            
            //ReadCommand
            if (txt_ReadCommand.Text.Trim().Equals(""))
            {
                MessageBox.Show("El campo 'Read Command' NO puede estar vacío. \n Por favor verifique e intente de nuevo.", "Unisys Duplicate Check", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            else{Configuration.readCommand = txt_ReadCommand.Text.Trim();}


            Configuration.Error_Message = cbx_Error.Checked ? true : false;
            Configuration.Information_Message = cbx_Information.Checked ? true : false;
            Configuration.Log_Message = cbx_Log.Checked ? true : false;
            Configuration.Process_Message = cbx_Process.Checked ? true : false;

            return true;
        }

        private void btn_Detener_Click(object sender, EventArgs e)
        {
            caller.EndInvoke(result);
            application.EndInvoke(result0);
        }

        private void dgv_Duplicates_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            
            string f = "";
            string c = "";
            
            if (e.ColumnIndex == 1)
            {
                fFields fields;
                if(dgv_Duplicates.CurrentCell.Value.ToString() == "")
                {
                    fields = new fFields();
                fields.ShowDialog();
              
                foreach (IndexField field in fields.listIndex)
                {
                    f += field.Name + ",";
                }

                f = f.Remove(f.Length - 1);
                dgv_Duplicates.CurrentCell.Value = f;
                
                } 
                else
                {
                    fFields field = new fFields(dgv_Duplicates.CurrentCell.Value.ToString().Split(','));
                  
                    
                    field.ShowDialog();
                }
                
            }
            if (e.ColumnIndex == 0)
            {
                if (dgv_Duplicates.CurrentCell.Value.ToString() == "")
                {
                    fClasses fClass = new fClasses();
                    fClass.ShowDialog();
                    if (fClass.listClass.Count > 0)
                    {
                        foreach (DocClasses docClass in fClass.listClass)
                        {
                            c += docClass.Class + ",";
                        }
                        c = c.Remove(c.Length - 1);
                        dgv_Duplicates.CurrentCell.Value = c;
                    }
                }
                else
                {
                    fClasses fClass = new fClasses(dgv_Duplicates.CurrentCell.Value.ToString().Split(','));
                    fClass.ShowDialog();
                }
            }
        }

        private void dgv_Inconsistencies_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            string f = "";
           
            if (e.ColumnIndex == 1)
            {
                fFields fields = new fFields();
                if (dgv_Inconsistencies.CurrentCell.Value.ToString() == "")
                {
                    fields.ShowDialog();

                    foreach (IndexField field in fields.listIndex)
                    {
                        f += field.Name + ",";
                    }

                    f = f.Remove(f.Length - 1);
                    dgv_Inconsistencies.CurrentCell.Value = f;
                }
                else {
                    fFields field = new fFields(dgv_Inconsistencies.CurrentCell.Value.ToString().Split(','));


                    field.ShowDialog();
                }
            }
        }

        private void btn_SaveRules_Click(object sender, EventArgs e)
        {

            IndexField fields;

            List<IndexField> listIndex;

            List<DocClass> listDocClass = new List<DocClass>();
            List<DocClassExc> listExc = new List<DocClassExc>();
            List<Rejected> listRejec = new List<Rejected>();
            List<Incosistence> listIncons = new List<Incosistence>();
           
            #region Duplicados

            if (dgv_Duplicates.RowCount > 1)
            {
                listDocClass = new List<DocClass>();
                for (int i = 0; i < dgv_Duplicates.RowCount - 1; i++)
                {
                    List<DocClasses> listDocClasses = new List<DocClasses>();

                    DocClass docClass = new DocClass();
                    DocClasses docClasses;

                    listIndex = new List<IndexField>();

                    string[] clases = dgv_Duplicates.Rows[i].Cells[0].Value.ToString().Split(',');
                    string[] campos = dgv_Duplicates.Rows[i].Cells[1].Value.ToString().Split(',');

                    foreach (string c in clases)
                    {
                        docClasses = new DocClasses();
                        docClasses.Class = c;
                        listDocClasses.Add(docClasses);

                    }
                    foreach (string d in campos)
                    {

                        fields = new IndexField();
                        fields.Name = d;
                        listIndex.Add(fields);
                    }

                    docClass.Classes = listDocClasses;
                    docClass.Fields = listIndex;
                    listDocClass.Add(docClass);
                }
            }
            
           


            #endregion

            #region Excepciones
            if (dgv_Exceptions.RowCount > 1)
            {
                for (int i = 0; i < dgv_Exceptions.RowCount - 1; i++)
                {

                    //string[] u = dgv_Exceptions.Rows[i].Cells[1].Value.ToString().Split(',');

                    DocClassExc docClassExc = new DocClassExc();
                    docClassExc.ClassName = dgv_Exceptions.Rows[i].Cells[0].Value.ToString();

                    docClassExc.UnitName = dgv_Exceptions.Rows[i].Cells[1].Value.ToString();
                    listExc.Add(docClassExc);
                    //foreach (string j in u)
                    //{
                    //    DocClassExc docClassExc = new DocClassExc();
                    //    docClassExc.ClassName = dgv_Exceptions.Rows[i].Cells[0].Value.ToString();

                    //    docClassExc.UnitName = j;
                    //    listExc.Add(docClassExc);
                    //}

                }
            }
            

            #endregion

            #region Inconsistencias
            if (dgv_Inconsistencies.RowCount > 1 )
            {
                for (int i = 0; i < dgv_Inconsistencies.RowCount - 1; i++)
                {
                    listIndex = new List<IndexField>();
                    Incosistence incosistence = new Incosistence();

                    incosistence.Name = dgv_Inconsistencies.Rows[i].Cells[0].Value.ToString();

                    string[] f = dgv_Inconsistencies.Rows[i].Cells[1].Value.ToString().Split(',');
                    foreach (string v in f)
                    {
                        //listIndex = new List<IndexField>();
                        fields = new IndexField();
                        fields.Name = v;
                        listIndex.Add(fields);
                    }

                    incosistence.Fields = listIndex;
                    listIncons.Add(incosistence);
                }
            }
            

            #endregion

            #region Rechazados
            if (dgv_Rejected.RowCount > 1)
            {
                for (int i = 0; i < dgv_Rejected.RowCount - 1; i++)
                {
                    Rejected rejec = new Rejected();
                    rejec.Name = dgv_Rejected.Rows[i].Cells[0].Value.ToString();
                    rejec.FieldName = dgv_Rejected.Rows[i].Cells[1].Value.ToString();
                    rejec.FieldValue = dgv_Rejected.Rows[i].Cells[2].Value.ToString();

                    listRejec.Add(rejec);
                }
            }
            
            #endregion

            DuplicateService duplicate = new DuplicateService();
            duplicate.DocClassList = listDocClass;
            duplicate.DocClassExcList = listExc;
            duplicate.IncosistenciesList = listIncons;
            duplicate.RejectedClass = listRejec;
            Serializer.XmlSerializeToFile<DuplicateService>(duplicate, txt_BussinessRules.Text.Trim());
            MessageBox.Show("Configuracion guardada");
        }

        private void txt_TimeOut_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Char.IsDigit(e.KeyChar))
            {
                e.Handled = false;
            }
            else if (Char.IsControl(e.KeyChar))
            {
                e.Handled = false;
            }
            else if (Char.IsSeparator(e.KeyChar))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

        

        private void DeserializerFile()
        {
            dupli = Deserializer.Deserialize<DuplicateService>(Configuration.duplicateRules);

                #region Duplicates
                foreach (DocClass docClass in dupli.DocClassList)
                {
                    string clase = "";
                    string campos = "";
                    foreach (DocClasses docClasses in docClass.Classes)
                    {
                        clase += docClasses.Class + ",";
                    }
                    foreach (IndexField ind in docClass.Fields)
                    {
                        campos += ind.Name + ",";
                    }
                    clase = clase.Remove(clase.Length - 1);
                    campos = campos.Remove(campos.Length - 1);

                    dgv_Duplicates.Rows.Add(clase, campos);
                }
                #endregion

            #region Exceptions
                string tmpClass = "";
            foreach(DocClassExc classExc in dupli.DocClassExcList)
            {

                tmpClass = classExc.ClassName;
                string units = classExc.UnitName;
                //if (dgv_Exceptions.Rows[0].Cells[0].Value.Equals(classExc.ClassName))
                //{
                //    units += classExc.UnitName + ",";
                //}
               dgv_Exceptions.Rows.Add(tmpClass,units);

            }
            #endregion

            #region Inconsistencies
            foreach (Incosistence incons in dupli.IncosistenciesList)
            {

                
                string campos = "";
                foreach (IndexField ind in incons.Fields)
                {
                    campos += ind.Name + ",";
                }
                campos = campos.Remove(campos.Length - 1);
                dgv_Inconsistencies.Rows.Add(incons.Name, campos);
            }
            #endregion

            #region Rejected
            foreach (Rejected rej in dupli.RejectedClass)
            {
                dgv_Rejected.Rows.Add(rej.Name, rej.FieldName, rej.FieldValue);
            }
            #endregion
        }
    }
}
